package com.ruoyi.app;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.CompanyInfo;
import com.ruoyi.system.dto.company.CompanyInfoAddDto;
import com.ruoyi.system.dto.company.CompanyInfoBindDto;
import com.ruoyi.system.service.ICompanyInfoService;
import com.ruoyi.workflow.constants.ApplyStatusConstant;
import com.ruoyi.workflow.domain.Message;
import com.ruoyi.workflow.myenum.MessageType;
import com.ruoyi.workflow.service.ICompanyApplyService;
import com.ruoyi.workflow.service.UserMessageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "(APP)单位信息API")
@RestController
@RequestMapping("/app/system/companyInfo")
public class CompanyInfoAppController extends BaseController {

    @Autowired
    private ICompanyInfoService companyInfoService;

    @Autowired
    private ICompanyApplyService companyApplyService;

    /**
     * 新增单位基本信息(APP端单位信息注册)
     */
    @ApiOperation("新增单位基本信息")
//    @PreAuthorize("@ss.hasPermi('system:companyInfo:add')")
    @Log(title = "单位基本信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult<CompanyInfo> addSave(@RequestBody CompanyInfoAddDto companyInfoAddDto) throws Exception {
        // 新增单位之前先查询数据是否存在
        String companyName = companyInfoAddDto.getCompanyName();
        // 根据单位名称查询不属于驳回状态的单位信息
        CompanyInfoBindDto companyInfoBindDto = companyInfoService.selectCompanyInfoByName(companyName);
        if (companyInfoBindDto != null) {
            // 单位存在的话就需要查询状态
            String applyStatus = companyInfoBindDto.getApplyStatus();
            if (applyStatus.equals(ApplyStatusConstant.UNDER_REVIEW_STR)) {
                return AjaxResult.success("该单位正处于审批中");
            } else if (applyStatus.equals(ApplyStatusConstant.COMPLETED_STR)) {
                return AjaxResult.success("该单位已经完成审批");
            }
        }
        // 单位信息不存在或者是单位信息处于被驳回的状态则需要开始新的审批流程
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long userId = user.getUserId();
        // 先写入单位的基本信息并设置注册标识为false
        CompanyInfo companyInfo = new CompanyInfo();
        BeanUtils.copyProperties(companyInfoAddDto, companyInfo);
        companyInfo.setCreatedAt(new Date());
        companyInfo.setCreatedBy(String.valueOf(userId));
        companyInfo.setRegisterStatus("false");
        companyInfoService.insertCompanyInfo(companyInfo);
        Long companyId = companyInfo.getCompanyId();
        // 新增完毕之后直接发起流程
        companyApplyService.startFlow(String.valueOf(companyId));
        return AjaxResult.success(companyInfo);
    }

    /**
     * 根据单位全称搜索单位基本信息(APP端绑定单位信息前先查询)
     */
    @ApiOperation("根据单位全称匹配单位基本信息")
    @GetMapping("/getByName")
    @ResponseBody
    public AjaxResult<CompanyInfoBindDto> getByName(@ApiParam(value = "单位名称") String companyName) {
        return AjaxResult.success(companyInfoService.selectCompanyInfoByName(companyName));
    }

    /**
     * 当前登录用户绑定单位(APP端登录用户绑定单位)
     *
     * @param companyId
     * @return
     */
    @ApiOperation("当前登录用户绑定单位")
//    @PreAuthorize("@ss.hasPermi('system:companyInfo:edit')")
    @Log(title = "单位基本信息", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/bind")
    public AjaxResult<String> editBind(@ApiParam(value = "单位ID") String companyId) {
        CompanyInfo info = companyInfoService.selectCompanyInfoById(Long.valueOf(companyId));
        if (!info.getRegisterStatus().equals("true")) {
            return AjaxResult.success("当前单位尚未审批通过，暂时无法绑定");
        }

        // 获取当前登录用户和系统时间
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long userId = user.getUserId();
        CompanyInfo companyInfo = new CompanyInfo();

        CompanyInfo selected = companyInfoService.selectCompanyInfoByUserId(String.valueOf(userId));
        if (selected != null) {
            return AjaxResult.success("当前用户已绑定了单位，暂时无法绑定");
        }

        // 先获取单位绑定的用户ID
        String userIdListStr = info.getUserId();

        // 设置绑定的用户ID列表
        if (userIdListStr == null){
            userIdListStr = userId + ",";
        }else {
            userIdListStr = userIdListStr + userId + ",";
        }

        // 设置登录用户
        companyInfo.setCompanyId(Long.valueOf(companyId));
        companyInfo.setUpdatedAt(new Date());
        companyInfo.setUpdatedBy(String.valueOf(userId));
        companyInfo.setUserId(userIdListStr);
        companyInfoService.updateCompanyInfo(companyInfo);
        return AjaxResult.success("绑定单位成功");
    }

    /**
     * 当前登录用户解绑单位(APP端解绑单位)
     *
     * @param
     * @return
     */
    @ApiOperation("当前登录用户解绑单位")
//    @PreAuthorize("@ss.hasPermi('system:companyInfo:edit')")
    @Log(title = "单位基本信息", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/unBind")
    public AjaxResult<String> editUnBind() {
        // 获取当前登录用户和系统时间
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long userId = user.getUserId();

        // 根据用户ID查询单位
        CompanyInfo info = companyInfoService.selectCompanyInfoByUserId(String.valueOf(userId));
        if (info == null) {
            return AjaxResult.success("该用户暂未绑定任何单位");
        }

        // 先获取单位绑定的用户ID列表字符串
        String userIdListStr = info.getUserId();

        // 拿到需要删除的用户ID
        String removeUserStr = userId + ",";

        // 得到最后的用户字符串
        String lastUserStr = removeUserFromList(userIdListStr, removeUserStr);

        // 设置登录用户
        info.setUserId(lastUserStr);
        info.setUpdatedAt(new Date());
        info.setUpdatedBy(String.valueOf(userId));
        companyInfoService.updateCompanyInfoUnBind(info);
        return AjaxResult.success("解绑单位成功");
    }

    /**
     * 根据用户ID查询是否绑定了单位基本信息(APP端的查询)
     */
    @ApiOperation("根据用户ID获取关联的单位信息")
    @GetMapping("/getByUserId/{userId}")
    @ResponseBody
    public AjaxResult<CompanyInfo> getByUserId(@ApiParam(value = "用户ID") @PathVariable("userId") String userId) {
        return AjaxResult.success(companyInfoService.selectCompanyInfoByUserId(userId));
    }

    /**
     * 根据登录信息查询绑定的单位信息(APP端的查询)
     */
    @ApiOperation("根据登录用户获取关联的单位信息")
    @GetMapping("/getBySelf")
    @ResponseBody
    public AjaxResult<CompanyInfo> getBySelf() {
        // 获取当前登录用户和系统时间
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long userId = user.getUserId();
        return AjaxResult.success(companyInfoService.selectCompanyInfoByUserId(String.valueOf(userId)));
    }


    /**
     * 移除用户字符串中指定的用户
     *
     * @param userIdListStr
     * @param removeUserStr
     * @return
     */
    public static String removeUserFromList(String userIdListStr, String removeUserStr) {
        // 去掉字符串末尾的逗号
        if (userIdListStr.endsWith(",")) {
            userIdListStr = userIdListStr.substring(0, userIdListStr.length() - 1);
        }

        if (removeUserStr.endsWith(",")) {
            removeUserStr = removeUserStr.substring(0, removeUserStr.length() - 1);
        }

        // 将字符串转换为List
        List<String> userIdList = Arrays.asList(userIdListStr.split(","));
        List<String> removeUserList = Arrays.asList(removeUserStr.split(","));

        // 过滤掉要移除的用户ID
        List<String> filteredUserIdList = userIdList.stream().filter(id -> !removeUserList.contains(id)).collect(Collectors.toList());

        // 检查过滤后的列表是否为空
        if (filteredUserIdList.isEmpty()) {
            return null;
        }

        // 将List转换回字符串
        return String.join(",", filteredUserIdList) + ",";
    }

    public static void main(String[] args) {
        String userIdListStr = "1,2,3,4,5,";
        String removeUserStr = "2,4,";
        System.out.println(removeUserFromList(userIdListStr, removeUserStr));
    }
}

